package me.kennylee.tongji;


import org.apache.http.Consts;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * <p> 发送API到请求 </p>
 * <p>Created on 3/11/2017.</p>
 *
 * @author kennylee
 */
public class DataApiConnection {

    private final String apiUrl;

    private DataApiConnection(String apiUrl) {
        super();
        this.apiUrl = apiUrl;
    }

    public static DataApiConnection newInstance(String apiUrl) {
        return new DataApiConnection(apiUrl);
    }

    /**
     * 发送请求
     *
     * @param request
     * @return json
     * @throws IOException
     */
    public String post(ApiRequest request) throws IOException {
        String json;
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(apiUrl);
            StringEntity se = new StringEntity(request.toJSON(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(se);
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                json = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        }
        return json;
    }

}
